<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Loader;
use think\Config;
use think\Db;

class Community extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("title")) {
            $map['title'] = ["like", "%" . $this->request->param("title") . "%"];
        }
        if ($this->request->param("address")) {
            $map['address'] = ["like", "%" . $this->request->param("address") . "%"];
        }
        if ($this->request->param("lxr")) {
            $map['lxr'] = ["like", "%" . $this->request->param("lxr") . "%"];
        }
        if ($this->request->param("lxr_dh")) {
            $map['lxr_dh'] = ["like", "%" . $this->request->param("lxr_dh") . "%"];
        }
    }

    public function map(){
        $this->view->assign('city', $this->request->param('city/s',''));
        $this->view->assign('lng', $this->request->param('lng/s',''));
        $this->view->assign('lat', $this->request->param('lat/s',''));

        return $this->view->fetch();

    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id'],'post');
            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }
            if( 0 < Db::name('community_user')->where(['account'=>$data['lxr_dh']])->count() ) {
                return ajax_return_adv_error('电话已经被占用');
            }
            $data['create_time'] = time();
            // 简单的直接使用db写入
            Db::startTrans();
            try {
                $ret = Db::name('community')->insertGetId($data);
                Db::name('community_user')->insert([
                    'account'=>$data['lxr_dh'],
                    'realname'=>$data['lxr'],
                    'password'=>password_hash_tp('88888888'),
                    'status'=>1,
                    'create_time'=>time(),
                    'is_admin'=>1,
                    'ty_id'=>$ret
                ]);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            }
            return ajax_return_adv('添加成功');
        } else {
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

}
